import React, {
      Children,
      cloneElement,
      Component,
      isValidElement,
} from "react";
import matchPath from "./matchPath";
import { RouterContext } from "./RouterContext";

export default class Switch extends Component {
      render() {
            return (
                  <RouterContext.Consumer>
                        {(context) => {
                              let { location } = context;
                              let match, element;
                              Children.forEach(this.props.children, (child) => {
                                    if (
                                          match == null &&
                                          isValidElement(child)
                                    ) {
                                          element = child;
                                          const { path } = child.props;
                                          match = path
                                                ? matchPath(
                                                        location.pathname,
                                                        child.props
                                                  )
                                                : context.match;
                                    }
                              });

                              return match
                                    ? cloneElement(element, {
                                            computedMatch: match,
                                      })
                                    : null;
                        }}
                  </RouterContext.Consumer>
            );
      }
}
